package com.wwp.wkb.base.impl;

import android.support.v7.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wwp.wkb.base.BaseRecycleView;

import java.util.List;

public abstract class BaseQueryRecycleView implements BaseRecycleView {
    protected RecyclerView recyclerView;
    protected BaseQuickAdapter adapter;
    protected RecyclerView.LayoutManager layoutManager;

    protected int page = 1;
    protected int pageSize = 10;   //一页请求多少条
    protected boolean hasMore = false;
    protected boolean enableMore = true;

    public BaseQueryRecycleView(RecyclerView recyclerView, BaseQuickAdapter adapter, RecyclerView.LayoutManager layoutManager) {
        this.recyclerView = recyclerView;
        this.adapter = adapter;
        this.layoutManager = layoutManager;
        init();
    }

    private void init() {
        enableMore = enableMore();
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    public <T> void onSucceed(List<T> list) {
        if (pageSize == 1) {
            if (list == null || list.size() == 0) {
                //删除列表中的旧数据，比如第一次第一页访问返回3条，第二次第一页访问返回0条
                if (adapter.getData() != null && adapter.getData().size() > 0) {
                    adapter.getData().clear();
                }
                onEmptyView();
            } else {
                adapter.setNewData(list);
                pageSize++;
            }
        } else {
            if (list != null) {
                adapter.addData(list);
                pageSize++;
            }
        }
        if (enableMore) {
            if (list == null || list.size() == 0) {
                hasMore = false;
            } else {
                hasMore = true;
            }
            if (hasMore) {
                adapter.loadMoreComplete();
            } else {
                adapter.loadMoreEnd();
            }
        }
        adapter.notifyDataSetChanged();
    }
}
